# coding=utf-8
# 代码文件：chapter9/ch9.2.8.py
import os

import itertools

from PyPDF2 import PdfFileReader, PdfFileWriter

# 设置输入目录
indir = r'data\in\加密'
#  设置输出目录
outdir = r'data\out'


# 查找dir目录下ext后缀名的文件列表
# dir参数是文件所在目录，ext参数是文件后缀名

def findext(dir, ext):
    allfile = os.listdir(dir)
    # 返回过滤器对象
    files_filter = filter(lambda x: x.endswith(ext), allfile)
    # 从过滤器对象提取列表
    list2 = list(files_filter)
    return list2  # 返回过滤后条件文件名


# 加密PDf函数
# namelist要加密文件列表
def decrypt_pdf(namelist):
    # 遍历每一个要加密的PDF文件
    for name in namelist:
        infile = os.path.join(indir, name)
        outfile = os.path.join(outdir, name)

        pdf_writer = PdfFileWriter()
        pdf_reader = PdfFileReader(infile)

        if pdf_reader.decrypt('qwerty'):
            print('解密成功！')

            for page_no in range(pdf_reader.getNumPages()):
                # 获得输入的PDF文档指定的页面对象
                page = pdf_reader.getPage(page_no)
                pdf_writer.addPage(page)

                # 写入文件
                with open(outfile, 'wb') as out:
                    pdf_writer.write(out)
        else:
            print('解密失败！')


if __name__ == '__main__':
    # 查找indir目录中所有PDF文件
    list2 = findext(indir, '.pdf')
    decrypt_pdf(list2)
    print('解密完成。')
